<template>
	<view class="user-center">
		
		<!-- 未登录状态 -->
		<view v-if="!isLoggedIn" class="login-prompt">
			<view class="avatar-container">
				<image class="login-avatar" src="/static/weidl.png" mode="aspectFill"></image>
			</view>
			<text class="welcome-text">欢迎使用</text>
			<text class="login-text">登录以享受更多功能</text>
			<view class="login-actions">
				<button class="login-btn" @click="goToLogin">登录</button>
				<button class="register-btn" @click="goToRegister">注册</button>
			</view>
		</view>

		<!-- 已登录状态 -->
		<template v-else>
			<!-- 用户信息头部 - 新设计 -->
			<view class="user-header-logged">
				<view class="user-profile">
					<view class="avatar-wrapper">
							<image class="avatar" src="/static/bo.png" mode="aspectFill"></image>
							<!-- <view :class="['vip-badge-mini', vipStatus ? 'vip-active' : '']">
								{{ vipStatus ? '超级会员' : '普通会员' }}
							</view> -->
						</view>
					<view class="user-details">
							<text class="username">{{ userInfo.nickname || '用户' }}</text>
							<text class="user-id">ID: {{ userInfo.userId || '----' }}</text>
									<text v-if="vipStatus && vipExpireDate" class="vip-expire">
										会员到期: {{ formatExpireDate(vipExpireDate) }}
									</text>
									<text v-if="vipStatus && checkVipExpiringSoon()" class="vip-warning">
										⚠️ 会员即将到期，请及时续费
									</text>
						</view>
				</view>
				<view class="user-status">
					<text class="status-text">在线</text>
					<view class="status-dot"></view>
				</view>
			</view>
		</template>
		<!-- 功能卡片区域 -->
		<view class="card-section">
			<!-- 会员卡片 -->
			<view class="card vip-card">
				<view class="card-header">
					<text class="card-title">会员中心</text>
					<view :class="['vip-badge', vipStatus ? 'vip-active' : '']">{{ vipStatus ? '超级会员' : '超级会员' }}</view>
				</view>
				<view class="vip-body">
					<image class="vip-icon" src="/static/vip.png" mode="aspectFit"></image>
					<view class="vip-content">
						<text class="vip-desc">开通会员享受更多特权</text>
						<text class="vip-benefit">• 无广告体验</text>
						<text class="vip-benefit">• 高速下载</text>
						<text class="vip-benefit">• 无限制下载次数</text>
						<text class="vip-benefit">• 更多高级功能</text>
					</view>
				</view>
				<button class="vip-btn" @click="openVip">立即开通</button>
			</view>

			<!-- 功能菜单 -->
			<view class="card menu-card">
				<!-- <view class="menu-item" @click="navigateToMyFavorites">
					<view class="menu-icon-wrapper favorites">
						<text class="menu-icon">❤️</text>
					</view>
					<text class="menu-text">我的收藏</text>
					<text class="menu-arrow">›</text>
				</view> -->
				<view class="menu-item" @click="navigateToHistory">
					<view class="menu-icon-wrapper history">
						<text class="menu-icon">🕒</text>
					</view>
					<text class="menu-text">浏览历史</text>
					<text class="menu-arrow">›</text>
				</view>

				<view class="menu-item" @click="navigateToHelp">
					<view class="menu-icon-wrapper help">
						<text class="menu-icon">❓</text>
					</view>
					<text class="menu-text">帮助与反馈</text>
					<text class="menu-arrow">›</text>
				</view>
			</view>

			<!-- 退出登录按钮（仅在登录状态显示） -->
			<view v-if="isLoggedIn" class="card logout-card">
				<button class="logout-btn" @click="handleLogout">退出登录</button>
			</view>
		</view>

		<!-- 版本信息 -->
		<view class="version-info">
			<text>版本 1.0.0</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isLoggedIn: false,
				userInfo: {},
				vipStatus: false,
				vipExpireDate: '',
				vipPackage: ''
			}
		},
		// 每次页面显示时检查登录状态并获取用户信息
		onShow() {
			this.checkLoginStatus();
			// 如果已登录，调用接口获取用户详细信息
			if (this.isLoggedIn) {
				this.fetchUserInfo();
			}
		},
		onLoad() {
			// 页面首次加载时也检查登录状态
			this.checkLoginStatus();
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				// 从本地存储获取登录信息
				const token = uni.getStorageSync('loginToken');
				const username = uni.getStorageSync('username');
				const userId = uni.getStorageSync('userId');
				
				if (token && username) {
					this.isLoggedIn = true;
					// 更新用户信息
					this.userInfo.nickname = username;
					this.userInfo.userId = userId;
					// 获取会员信息
					this.vipStatus = uni.getStorageSync('isVip');
					this.vipExpireDate = uni.getStorageSync('vipExpireDate');
					this.vipPackage = uni.getStorageSync('vipPackage');
					// 获取更详细的用户信息
					this.getUserInfo();
				}
			},
			
			// 获取用户信息（模拟）
			getUserInfo() {
				// 模拟API调用获取用户信息
				// 实际开发中应从服务器或本地存储获取
				console.log('获取用户信息');
			},
			
			// 从服务器获取用户详细信息（不使用缓存，确保最新数据）
		fetchUserInfo() {
			const token = uni.getStorageSync('loginToken');
			if (!token) {
				console.error('缺少登录凭证，将跳转到登录页面');
				uni.showToast({
					title: '请重新登录',
					icon: 'none',
					duration: 1500
				});
				// 3秒后跳转到登录页面
				setTimeout(() => {
					this.goToLogin();
				}, 3000);
				return;
			}
			
			uni.showLoading({
				title: '加载中...'
			});
			
			// 添加随机数参数，完全避免缓存
			const randomNum = Math.floor(Math.random() * 1000000);
			
			uni.request({
				url: 'https://qyapi.ipaybuy.cn/api/get_user',
				method: 'GET',
				header: {
					'token': token,
					'content-type': 'application/json',
					'Cache-Control': 'no-cache, no-store, must-revalidate',
					'Pragma': 'no-cache',
					'Expires': '0'
				},
				data: {
					timestamp: new Date().getTime(),
					random: randomNum
				},
				success: (res) => {
					console.log('用户信息接口返回:', res.data);
					if (res.statusCode === 200 && res.data && res.data.code === 200) {
						// 正确解析API响应格式
						const userData = res.data.data || {};
						
						// 全面更新用户信息
						this.userInfo = {
							...this.userInfo,
							nickname: userData.email || `用户${userData.id}`,
							userId: userData.id ? userData.id.toString() : '',
							email: userData.email || '',
							appId: userData.appId || '',
							appKey: userData.appKey || ''
						};
						
						// 精确更新VIP信息
						this.vipStatus = userData.vipId > 0;
						this.vipExpireDate = userData.vipTime ? userData.vipTime : '';
						this.vipPackage = userData.vip && userData.vip.name ? userData.vip.name : '';
						
						// 更新本地存储，保存完整信息
						const storageData = {
							userId: userData.id ? userData.id.toString() : '',
							username: userData.email || '',
							isVip: this.vipStatus,
							vipExpireDate: this.vipExpireDate,
							vipPackage: this.vipPackage,
							appId: userData.appId || '',
							appKey: userData.appKey || ''
						};
						
						// 循环保存所有信息到本地存储
						for (const [key, value] of Object.entries(storageData)) {
							uni.setStorageSync(key, value);
						}
						
						console.log('用户信息更新成功');
					} else if (res.data && res.data.code === 401) {
						// Token过期或无效
						console.error('Token已过期，请重新登录');
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: 'none',
							duration: 2000
						});
						// 清除过期的登录信息
						this.clearLoginData();
						// 跳转到登录页面
						setTimeout(() => {
							this.goToLogin();
						}, 2000);
					} else {
						// 其他错误
						const errorMsg = res.data?.msg || '获取用户信息失败';
						console.error('获取用户信息失败:', errorMsg);
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 2000
						});
					}
				},
				fail: (err) => {
					console.error('获取用户信息网络请求失败:', err);
					// 网络请求失败，尝试使用本地存储的信息
					uni.showToast({
						title: '网络异常，使用本地数据',
						icon: 'none',
						duration: 2000
					});
					// 重试一次请求
					this.retryFetchUserInfo(token, randomNum);
				},
				complete: () => {
					uni.hideLoading();
				}
			});
		},
		
		// 重试获取用户信息
		retryFetchUserInfo(token, originalRandomNum) {
			// 500ms后重试，使用不同的随机数
			setTimeout(() => {
				const newRandomNum = Math.floor(Math.random() * 1000000);
				uni.request({
					url: 'https://qyapi.ipaybuy.cn/api/get_user',
					method: 'GET',
					header: {
						'token': token,
						'content-type': 'application/json',
						'Cache-Control': 'no-cache'
					},
					data: {
						timestamp: new Date().getTime(),
						random: newRandomNum
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							// 成功后更新数据
							const userData = res.data.data || {};
							this.userInfo.nickname = userData.email || `用户${userData.id}`;
							this.userInfo.userId = userData.id ? userData.id.toString() : '';
							this.vipStatus = userData.vipId > 0;
							this.vipExpireDate = userData.vipTime || '';
							console.log('重试获取用户信息成功');
						}
					},
					fail: (err) => {
						console.error('重试获取用户信息失败:', err);
					}
				});
			}, 500);
		},
		
		// 清除登录数据
			clearLoginData() {
				const keysToRemove = ['loginToken', 'userId', 'username', 'isVip', 'vipExpireDate', 'vipPackage', 'appId', 'appKey'];
				keysToRemove.forEach(key => {
					uni.removeStorageSync(key);
				});
				// 重置页面状态
				this.isLoggedIn = false;
				this.userInfo = {};
				this.vipStatus = false;
				this.vipExpireDate = '';
				this.vipPackage = '';
			},
			
			// 格式化日期显示
			formatExpireDate(dateString) {
				if (!dateString) return '永久有效';
				
				try {
					const date = new Date(dateString);
					// 检查日期是否有效
					if (isNaN(date.getTime())) {
						return dateString; // 如果日期无效，返回原始字符串
					}
					
					// 格式化日期为 YYYY-MM-DD HH:MM 格式
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					
					return `${year}-${month}-${day} ${hours}:${minutes}`;
				} catch (error) {
					console.error('日期格式化错误:', error);
					return dateString;
				}
			},
			
			// 检查VIP是否即将到期（7天内）
			checkVipExpiringSoon() {
				if (!this.vipExpireDate) return false;
				
				try {
					const expireDate = new Date(this.vipExpireDate);
					const now = new Date();
					const daysUntilExpire = Math.ceil((expireDate - now) / (1000 * 60 * 60 * 24));
					
					return daysUntilExpire > 0 && daysUntilExpire <= 7;
				} catch (error) {
					return false;
				}
			},
			
			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			},
			
			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/addUser/addUser'
				});
			},

			// 导航到我的收藏
			navigateToMyFavorites() {
				uni.showToast({
					title: '我的收藏页面',
					icon: 'none',
					duration: 1500
				});
				// 实际开发中使用导航
				// uni.navigateTo({ url: '/pages/favorites/favorites' });
			},

			// 导航到浏览历史
			navigateToHistory() {
				uni.navigateTo({
					url: '/pages/record/record'
				});
			},



			// 导航到帮助与反馈
			navigateToHelp() {
				uni.showToast({
					title: '帮助与反馈页面',
					icon: 'none',
					duration: 1500
				});
				// 实际开发中使用导航
				// uni.navigateTo({ url: '/pages/help/help' });
			},

			// 开通会员
			openVip() {
				uni.navigateTo({
					url: '/pages/vip/vip'
				});
			},
			
			// 格式化到期日期
			formatExpireDate(dateString) {
				if (!dateString) return '';
				const date = new Date(dateString);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 退出登录
			handleLogout() {
				uni.showModal({
					title: '确认退出',
					content: '确定要退出登录吗？',
					confirmText: '确定',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							// 调用清除登录数据方法
							this.clearLoginData();
							
							// 显示退出成功提示
							uni.showToast({
								title: '退出成功',
								icon: 'success',
								duration: 1500
							});
							
							// 延迟跳转到登录页面
							setTimeout(() => {
								// 使用redirectTo而不是navigateTo，避免用户可以返回到已退出的页面
								uni.redirectTo({
									url: '/pages/login/login'
								});
							}, 1500);
						}
				}
			});
			}
		}
	}
</script>

<style scoped>
	/* 全局样式 - 移除顶部白色区域 */
	.user-center {
		min-height: 100vh;
		background-color: #f5f7fa;
		position: relative;
		padding-bottom: 60rpx; /* 为底部添加足够的间距 */
		margin-top: 0;
		padding-top: 26rpx;
	}
	
	/* 确保页面无默认边距 */
	page {
		background-color: #f5f7fa;
		margin: 0;
		padding: 0;
	}
	
	/* 重置可能导致顶部空白的元素 */
	* {
		margin: 0;
		padding: 0;
	}
	
	/* 移除顶部渐变背景相关的白色区域 */
	.user-header-logged {
		margin-top: 0rpx;
	}
	
	/* 未登录状态样式 */
	.login-prompt {
		position: relative;
		z-index: 2;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: white;
		margin: 0rpx 30rpx 30rpx 30rpx;
		padding: 50rpx 30rpx;
		border-radius:20rpx; /* 顶部无圆角 */
		box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}
	
	.avatar-container {
		position: relative;
		margin-bottom: 20rpx;
	}
	
	.login-avatar {
		width: 160rpx;
		height: 160rpx;
		border-radius: 80rpx;
		border: 6rpx solid rgba(255, 255, 255, 0.9);
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
	}
	
	.welcome-text {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.login-text {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 30rpx;
	}
	
	.login-actions {
		display: flex;
		gap: 30rpx;
		width: 100%;
		max-width: 500rpx;
		margin-top: 10rpx;
	}
	
	.login-btn,
	.register-btn {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		font-size: 32rpx;
		font-weight: 600;
		border-radius: 44rpx;
		padding: 0;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		border: none;
	}
	
	.login-btn {
		background: linear-gradient(135deg, #007AFF, #0056D6);
		color: white;
	}
	
	.login-btn:active {
		background: linear-gradient(135deg, #0056D6, #003F91);
		transform: scale(0.96);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
	}
	
	.register-btn {
		background: linear-gradient(135deg, #4CD964, #2ECC71);
		color: white;
	}
	
	.register-btn:active {
		background: linear-gradient(135deg, #2ECC71, #27AE60);
		transform: scale(0.96);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
	}

	/* 已登录用户信息头部 - 新样式 */
	.user-header-logged {
		position: relative;
		z-index: 2;
		margin: 0rpx 30rpx 30rpx 30rpx;
		padding: 30rpx;
		background: rgba(255, 255, 255, 0.95);
		border-radius:20rpx; /* 顶部无圆角 */
		box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.user-profile {
		display: flex;
		align-items: center;
	}
	
	.avatar-wrapper {
		position: relative;
		margin-right: 24rpx;
	}
	
	.user-header-logged .avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 70rpx;
		border: 4rpx solid #007AFF;
	}
	
	.vip-badge-mini {
				position: absolute;
				bottom: 0;
				right: 0;
				background-color: #ff6b6b;
				color: white;
				padding: 4rpx 12rpx;
				border-radius: 12rpx;
				font-size: 20rpx;
				font-weight: 500;
				border: 2rpx solid white;
			}
			
			/* 超级会员徽章样式 */
			.vip-badge-mini.vip-active {
				background: linear-gradient(135deg, #ff9f43, #ff6b6b);
				font-weight: bold;
			}
			
			/* 会员到期时间样式 */
			.vip-expire {
				font-size: 24rpx;
				color: #ff6b6b;
				margin-top: 6rpx;
				display: block;
			}
	
	.user-details {
		display: flex;
		flex-direction: column;
	}
	
	.user-header-logged .username {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.user-header-logged .user-id {
		font-size: 24rpx;
		color: #666;
	}
	
	.vip-expire {
		font-size: 24rpx;
		color: #ff9500;
		margin-bottom: 4rpx;
	}
	
	.vip-warning {
		font-size: 24rpx;
		color: #ff4d4f;
		font-weight: 500;
		background-color: rgba(255, 77, 79, 0.1);
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
		margin-top: 8rpx;
		animation: pulse 2s infinite;
	}
	
	.user-status {
		display: flex;
		align-items: center;
		background-color: #e8f5e9;
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
	}
	
	.status-text {
		font-size: 24rpx;
		color: #4caf50;
		margin-right: 8rpx;
	}
	
	.status-dot {
		width: 16rpx;
		height: 16rpx;
		border-radius: 8rpx;
		background-color: #4caf50;
		animation: pulse 2s infinite;
	}
	
	@keyframes pulse {
		0% {
			transform: scale(1);
			opacity: 1;
		}
		50% {
			transform: scale(1.2);
			opacity: 0.8;
		}
		100% {
			transform: scale(1);
			opacity: 1;
		}
	}
	
	/* 用户统计数据 */
	.user-stats {
		display: flex;
		background-color: rgba(255, 255, 255, 0.95);
		border-radius: 16rpx;
		padding: 20rpx 40rpx;
		margin-top: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}
	
	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 0 40rpx;
	}
	
	.stat-item:not(:last-child) {
		border-right: 1rpx solid #e0e0e0;
	}
	
	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 5rpx;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #666;
	}

	/* 卡片通用样式 */
	.card-section {
		position: relative;
		z-index: 2;
		padding: 0 30rpx;
		margin-bottom: 20rpx;
	}
	
	.card {
		background-color: white;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 28rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}
	
	.card:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
	}
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}
	
	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	/* 会员卡片 */
	.vip-card {
		background: linear-gradient(135deg, #fff8e1, #fff3cd);
		border-left: 10rpx solid #ffc107;
	}
	
	.vip-badge {
		background-color: #ff6b6b;
		color: white;
		padding: 6rpx 16rpx;
		border-radius: 16rpx;
		font-size: 24rpx;
		font-weight: 500;
	}
	
	.vip-badge.vip-active {
		background: linear-gradient(135deg, #ff9f43, #ff6b6b);
		font-weight: bold;
	}
	
	.vip-body {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.vip-icon {
		width: 120rpx;
		height: 120rpx;
		border-radius: 16rpx;
	}
	
	.vip-content {
		flex: 1;
		margin: 0 24rpx;
	}
	
	.vip-desc {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.vip-benefit {
		font-size: 24rpx;
		color: #666;
		line-height: 36rpx;
		display: block;
	}
	
	.vip-btn {
		background-color: #ff9f43;
		color: white;
		font-size: 30rpx;
		font-weight: 600;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		border: none;
		transition: all 0.3s ease;
	}
	
	.vip-btn:active {
		background-color: #ee8a2a;
		transform: scale(0.98);
	}
	
	/* 功能菜单 */
	.menu-card {
		padding: 0;
		position: relative;
		z-index: 2;
	}
	
	.menu-item {
		display: flex;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		transition: all 0.2s ease;
	}
	
	.menu-item:last-child {
		border-bottom: none;
	}
	
	.menu-item:active {
		background-color: #f8f8f8;
	}
	
	.menu-icon-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 70rpx;
		height: 70rpx;
		border-radius: 14rpx;
		margin-right: 24rpx;
	}
	
	.menu-icon-wrapper.favorites {
		background-color: #ffebee;
	}
	
	.menu-icon-wrapper.history {
		background-color: #e3f2fd;
	}
	
	
	
	.menu-icon-wrapper.help {
		background-color: #fff3e0;
	}
	
	.menu-icon {
		font-size: 40rpx;
	}
	
	.menu-text {
		flex: 1;
		font-size: 32rpx;
		color: #333;
	}
	
	.menu-arrow {
		font-size: 36rpx;
		color: #ccc;
	}
	
	/* 退出登录按钮 */
	.logout-card {
		padding: 0;
	}
	
	.logout-btn {
		background-color: white;
		color: #e64340;
		font-size: 32rpx;
		font-weight: 500;
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 16rpx;
		border: 2rpx solid #e64340;
		transition: all 0.3s ease;
	}
	
	.logout-btn:active {
		background-color: #fef0f0;
		transform: scale(0.98);
	}
	
	/* 版本信息 */
	.version-info {
		position: relative;
		z-index: 2;
		padding: 40rpx 0;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		margin-top: 40rpx;
		background-color: #f5f7fa;
	}
	
	/* 响应式调整 */
	@media (max-width: 320px) {
		.login-actions {
			gap: 20rpx;
		}
	}
</style>